<template>
  <div id="wrapper" ref="wrapper">
    <mu-appbar title="lan" style="-webkit-app-region: drag">
      <mu-icon-button icon="settings_input_antenna" slot="left" style="-webkit-app-region: no-drag"/>
      
      <mu-icon-menu icon="more_vert" slot="right" tooltip="更多操作" style="-webkit-app-region: no-drag">
        <mu-menu-item v-if="showLastDir && !showServer" title="上次" tooltip="打开上次的目录" :desktop="true" @click="openLastServerFolder" style="-webkit-app-region: no-drag"/>
        <mu-menu-item title="关于" style="-webkit-app-region: no-drag"/>
      </mu-icon-menu>
      <mu-icon-button icon="remove" @click="minimize" slot="right" tooltip="最小化" style="-webkit-app-region: no-drag"/>
      <mu-icon-button icon="close" @click="close" slot="right" tooltip="退出" style="-webkit-app-region: no-drag"/>
    </mu-appbar>

    <div class="server_content">
      <div id="drop_div" ref="select_frame" v-show="showServer == false">
        拖动文件夹到该区域
      </div>
      <div id="server_div" v-show="showServer == true">
        <mu-card>
          <mu-card-header :title="iCurrentWindow.mUrl" :subTitle="iCurrentWindow.mRootPath">            
            <mu-icon-button icon="blur_on" class="qr_btn" tooltip="显示二维码" @click="openBottomPopup"/>
          </mu-card-header>
          <mu-card-actions>
            <mu-flat-button @click="stopServer" label="停止服务" tooltip="停止服务"/>
            <mu-flat-button @click="openInBrowser" label="浏览器中打开" tooltip="浏览器中打开"/>
          </mu-card-actions>
        </mu-card>
        <div class="webview">
          <webview ref="webview" :src="iCurrentWindow.mUrl" style="width:100%; height:100%;"></webview>
        </div>
      </div>
    </div> 

    <div class="add_dir_button">
      <mu-float-button @click="choiceServerFolder" v-show="showServer == false" icon="add" tooltip="选择文件夹"/>
    </div>

    <mu-snackbar v-if="snackbar" :message="snackbarMessage" action="关闭" @actionClick="hideSnackbar" @close="hideSnackbar"/>

    <mu-popup position="bottom" :overlay="true" popupClass="demo-popup-bottom" :open="bottomPopup" @close="closeBottomPopup">
      <mu-appbar title="手机浏览器扫描二维码">
        <mu-flat-button slot="right" label="关闭" color="white" @click="closeBottomPopup"/>
      </mu-appbar>
      <mu-content-block>
        <qrcode-vue :value="qrcodeUrl" :size="200" level="H"></qrcode-vue>
      </mu-content-block>
    </mu-popup>
  </div>
</template>


<script>
import Express from "../express";
import fs from "fs";
import settings from 'electron-settings';
import QrcodeVue from 'qrcode.vue';
import kill from 'kill-port';

export default {
  name: "main-page",
  components: {
    QrcodeVue
  },
  data() {
    return {
      showServer: false,
      showLastDir: false,
      bottomPopup: false,
      lastDir: '',
      lastPort: '',
      qrcodeUrl: '',
      iCurrentWindow: {

      },
      snackbar: false,
      snackbarMessage: ''
    };
  },
  methods: {
    close() {
      this.$electron.remote.BrowserWindow.getFocusedWindow().close();
    },
    minimize() {
      this.$electron.remote.BrowserWindow.getFocusedWindow().minimize();
    },
    stopServer() {
      const _this = this;      

      Express.closeServer(function() {
        kill(_this.iCurrentWindow.mPort);
        _this.showServer = false;
        _this.iCurrentWindow = {};
      });
    },
    openInBrowser() {
      this.$electron.shell.openExternal(this.iCurrentWindow.mUrl);
    },
    openBottomPopup() {
      this.qrcodeUrl = this.iCurrentWindow.mUrl;
      this.bottomPopup = true;
    },
    closeBottomPopup() {
      this.bottomPopup = false;
    },
    showSnackbar (message) {
      this.snackbarMessage = message;
      this.snackbar = true;
      
      if (this.snackTimer) clearTimeout(this.snackTimer);
      this.snackTimer = setTimeout(() => { this.snackbar = false }, 2000);
    },
    hideSnackbar () {
      this.snackbar = false;
      if (this.snackTimer) clearTimeout(this.snackTimer);
    },
    startServer: function(path, port) {
      if (this.showServer) {
        this.showSnackbar('当前有正在运行的服务，请先停止！');
        return;
      }

      const _this = this;
      Express.emptyPort(
        {
          customPort: port ? port : 12520,
          startPort: 6048,
          maxPort: 65535
        },
        function(oError, iGivenPort) {
          const mPort = iGivenPort || 12345;
          Express.startServer(path, mPort, "", function(e) {
            if (e instanceof Error) {
              console.error(e);
            } else {
              _this.showServer = true;
              _this.iCurrentWindow = e;
              settings.set('setting', {
                'serverDir': e.mRootPath,
                'serverPort': e.mPort
              });
            }
          });
        }
      );
    },
    choiceServerFolder() {
      const _this = this;
      this.$electron.remote.dialog.showOpenDialog(
        { properties: ["openDirectory"] },
        function(e) {
          if (e) {
            const path = e[0];

            _this.startServer(path);
          }
        }
      );
    },
    openLastServerFolder() {
      if (fs.existsSync(this.lastDir)) {
        this.startServer(this.lastDir, this.lastPort);
      } else {
        settings.delete('setting');
      }
    }
  },
  created: function() {},
  mounted() {
    if (settings.has('setting')) {
      this.showLastDir = true;
      this.lastDir = settings.get('setting.serverDir');
      this.lastPort = settings.get('setting.serverPort');
    } 

    window.ondragover = function(e) {
      e.preventDefault();
      return false;
    };

    window.ondrop = function(e) {
      e.preventDefault();
      return false;
    };

    this.$refs.webview.addEventListener('new-window', (e) => { 
      const protocol = require('url').parse(e.url).protocol;
      // console.log(e.url);
      // return; 
      if (protocol === 'http:' || protocol === 'https:') {
        console.log(e.url);
        this.qrcodeUrl = e.url;
        this.bottomPopup = true;
        //shell.openExternal(e.url)
        // window.open(e.url)
      }
    });

    this.$refs.select_frame.ondragover = e => {
      if (this.showServer == false) {
        this.$refs.select_frame.style.border = "2px dashed red";
      }
      return false;
    };
    this.$refs.select_frame.ondragleave = e => {
      if (this.showServer == false) {
        this.$refs.select_frame.style.border = "1px dashed #ccc";
      }
      return false;
    };
    this.$refs.select_frame.ondrop = e => {
      e.preventDefault();

      if (this.showServer == false) {
        this.$refs.select_frame.style.border = "1px dashed #ccc";
        if (e.dataTransfer.files.length > 0) {
          var file = e.dataTransfer.files[0];

          var stat = fs.statSync(file.path);
          if (stat.isDirectory()) {
            const path = file.path;

            this.startServer(path);
          } else {
            this.showSnackbar('请选择文件夹拖入该区域');
          }
        }
      }

      return false;
    };
  }
};
</script>

<style>
#wrapper {
  overflow: hidden;
  position: relative;
}
.server_content {
  height: 540px;
  width: 100%;
}
.webview {
  height: 500px;
  width: 100%;
}

.add_dir_button {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

#drop_div {
  margin: 20px;
  border: 1px dashed #ccc;
  height: 500px;
  line-height: 500px;
  text-align: center;
  font-size: 16px;
}
#server_div {
  width: 100%;
}
.qr_btn {
  float: right
}
.demo-popup-bottom {
  width: 100%;
  text-align: center;
  max-width: 330px;
}
</style>